package com.antler.smt.admin.service.impl;

import com.antler.smt.admin.mapper.PermissionEntityMapper;
import com.antler.smt.admin.mapper.PermissionInfoMapper;
import com.antler.smt.admin.mapper.RolePermissionInfoMapper;
import com.antler.smt.admin.mapper.UserInfoMapper;
import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.PermissionConstant;
import com.antler.smt.entity.PermissionEntity;
import com.antler.smt.entity.RolePermissionEntity;
import com.antler.smt.enums.PermissionTypeEnum;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.enums.TopPermissionEnum;
import com.antler.smt.exception.TransactionException;
import com.antler.smt.request.admin.AddPermissionReq;
import com.antler.smt.request.admin.GetPermissionListReq;
import com.antler.smt.request.admin.UpdatePermissionReq;
import com.antler.smt.response.admin.GetPermissionTreeResp;
import com.antler.smt.response.admin.GetRoleListResp;
import com.antler.smt.response.admin.ListPermissionResp;
import com.antler.smt.response.admin.ZtreeResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.service.admin.PermissionService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限接口实现
 *
 * @author vic
 * @date 2018-04-13 14:55
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    /**
     * 权限信息Mapper
     */
    @Autowired
    private PermissionInfoMapper permissionInfoMapper;

    @Autowired
    private PermissionEntityMapper permissionEntityMapper;

    /**
     * 角色权限Mapper
     */
    @Autowired
    private RolePermissionInfoMapper rolePermissionInfoMapper;

    /**
     * 用户Mapper
     */
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 获取权限列表信息
     *
     * @return 权限列表
     */
    @Override
    public List<ListPermissionResp> listPerms() {
        return permissionInfoMapper.listPerms();
    }

    /**
     * 新增权限
     *
     * @param req 请求实体
     * @return Result实体
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result addPermission(AddPermissionReq req) {
        Result result = new Result();
        PermissionEntity permissionEntity = new PermissionEntity();
        permissionEntity.setName(req.getName());
        permissionEntity.setType(req.getType());
        permissionEntity.setParentId(req.getParentId());
        permissionEntity.setPerms(req.getPerms());
        permissionEntity.setOrderNum(req.getOrderNum());
        int insertSelective = permissionEntityMapper.insertSelective(permissionEntity);
        if (insertSelective <= 0) {
            throw new TransactionException(ResultCodeEnum.APPEND_DATA_ERROR, "新增权限表失败！");
        }
        return result;
    }


    /**
     * 获取权限列表信息
     *
     * @param request 请求实体
     * @return 角色列表实体
     */
    @Override
    public Result<PageInfo<ListPermissionResp>> listPermissionInfo(GetPermissionListReq request) {
        Result result;
        PageHelper.startPage(request.getPageCurrent(), request.getPageSize());
        Page<ListPermissionResp> listRoleInfo = permissionInfoMapper.listPermissionInfo(request);
        if (listRoleInfo != null) {
            PageInfo<GetRoleListResp> roleListPageInfo = new PageInfo(listRoleInfo);
            result = new Result(roleListPageInfo);
        } else {
            result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "查询数据为空！");
        }
        return result;
    }


    /**
     * 递归获取权限集合
     *
     * @return
     */
    @Override
    public Result<List<GetPermissionTreeResp>> getAllPermList() {
        Result result;
        List<GetPermissionTreeResp> permList = permissionInfoMapper.getPermissionInfoByParentId(0L);
        if (permList != null) {
            for (GetPermissionTreeResp perm : permList) {
                List<GetPermissionTreeResp> children = permissionInfoMapper.getPermissionInfoByParentId(perm.getPermissionId());
                setChildren(children);
                perm.setChildren(children);
            }
            result = new Result(permList);
        } else {
            result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "查询数据为空！");
        }
        return result;
    }

    /**
     * 递归获取权限集合加默认选中
     *
     * @param id 角色id
     * @return
     */
    @Override
    public Result<List<GetPermissionTreeResp>> getAllPermListChecked(Long id) {
        Result result;
        //查role_permission表
        List<RolePermissionEntity> rolePermList = rolePermissionInfoMapper.selectByRoleId(id);
        List<GetPermissionTreeResp> permList = permissionInfoMapper.getPermissionInfoByParentId(0L);
        if (permList != null) {
            for (GetPermissionTreeResp perm : permList) {
                List<GetPermissionTreeResp> children = permissionInfoMapper.getPermissionInfoByParentId(perm.getPermissionId());
                if (rolePermList != null && !rolePermList.isEmpty()) {
                    for (RolePermissionEntity rolePermissionEntity : rolePermList) {
                        if (perm.getPermissionId().equals(rolePermissionEntity.getPermissionId())) {
                        }
                    }
                }
                setChildrenChecked(children, rolePermList);
                perm.setChildren(children);
            }
            result = new Result(permList);
        } else {
            result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "查询数据为空！");
        }
        return result;
    }

    /**
     * 根据父Id设置子集合
     *
     * @param permList 权限列表
     */
    public void setChildren(List<GetPermissionTreeResp> permList) {
        for (GetPermissionTreeResp perm : permList) {
            List<GetPermissionTreeResp> children = permissionInfoMapper.getPermissionInfoByParentId(perm.getPermissionId());
            setChildren(children);
            perm.setChildren(children);
        }
    }

    /**
     * 根据父Id设置子集合加默认选中
     *
     * @param permEntities           权限实体
     * @param rolePermissionEntities 角色权限实体
     */
    public void setChildrenChecked(List<GetPermissionTreeResp> permEntities, List<RolePermissionEntity> rolePermissionEntities) {
        for (GetPermissionTreeResp perm : permEntities) {
            List<GetPermissionTreeResp> children = permissionInfoMapper.getPermissionInfoByParentId(perm.getPermissionId());
            if (rolePermissionEntities != null && rolePermissionEntities.size() > 0) {
                for (RolePermissionEntity rolePermissionEntity : rolePermissionEntities) {
                    if (perm.getPermissionId().equals(rolePermissionEntity.getPermissionId())) {
                    }
                }
            }
            setChildrenChecked(children, rolePermissionEntities);
            perm.setChildren(children);
        }
    }

    /**
     * 获取权限树
     *
     * @return
     */
    @Override
    public Result<List<ZtreeResp>> treePerms() {
        Result result;
        List<ListPermissionResp> permissionList = permissionInfoMapper.listPerms();
        List<ZtreeResp> zTreeBeans = new ArrayList<>();
        if (permissionList != null && !permissionList.isEmpty()) {
            for (ListPermissionResp permissionResp : permissionList) {
                ZtreeResp tree = new ZtreeResp();
                tree.setpId(permissionResp.getParentId());
                tree.setName(permissionResp.getName());
                tree.setOpen(false);
                tree.setChkDisabled(false);
                tree.setId(permissionResp.getId());
                zTreeBeans.add(tree);
            }
        }
        return new Result<>(zTreeBeans);
    }

    /**
     * 获取用户权限
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<GetPermissionTreeResp> getUserPermissionList(Long userId) {
        //系统管理员，拥有最高权限
        if (PermissionConstant.SUPER_ADMIN.equals(userId)) {
            return getAllPermissionList(null);
        }
        //用户菜单列表
        List<Long> menuIdList = userInfoMapper.queryAllPermissionId(userId);
        return getAllPermissionList(menuIdList);
    }

    /**
     * 更新权限
     *
     * @param req 请求实体
     * @return Result实体
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result updatePermission(UpdatePermissionReq req) {
        Result result = new Result();
        PermissionEntity permissionEntity = new PermissionEntity();
        permissionEntity.setId(req.getPermissionId());
        permissionEntity.setName(req.getName());
        permissionEntity.setType(req.getType());
        permissionEntity.setParentId(req.getParentId());
        permissionEntity.setPerms(req.getPerms());
        permissionEntity.setOrderNum(req.getOrderNum());
        int updateSelective = permissionEntityMapper.updateByPrimaryKeySelective(permissionEntity);
        if (updateSelective <= 0) {
            throw new TransactionException(ResultCodeEnum.MODIFY_DATA_ERROR, "更新权限表失败！");
        }
        return result;
    }

    /**
     * 删除权限
     *
     * @param permissionId 权限id
     * @return Result实体
     */
    @Override
    public Result deletePermission(Long permissionId) {
        Result result = new Result();
        int deleteByPrimaryKey = permissionEntityMapper.deleteByPrimaryKey(permissionId);
        if (deleteByPrimaryKey <= 0) {
            throw new TransactionException(ResultCodeEnum.DELETE_DATA_ERROR, "删除权限表失败！");
        }
        return result;
    }

    /**
     * 获取不包含按钮的权限列表
     *
     * @return Result实体
     */
    @Override
    public Result<List<ZtreeResp>> queryNotButtonList() {
        //查询列表数据
        List<ListPermissionResp> permissionList = permissionInfoMapper.queryNotButtonList();
        List<ZtreeResp> ztreeBeans = new ArrayList<>();
        //添加顶级菜单
        ZtreeResp root = new ZtreeResp();
        root.setId(TopPermissionEnum.TopMenu.key().longValue());
        root.setName(TopPermissionEnum.TopMenu.desc());
        root.setpId(-1L);
        root.setOpen(true);
        ztreeBeans.add(root);
        for (ListPermissionResp permissionResp : permissionList) {
            ZtreeResp tree = new ZtreeResp();
            tree.setId(permissionResp.getId());
            tree.setpId(permissionResp.getParentId());
            tree.setName(permissionResp.getName());
            tree.setOpen(false);
            tree.setChkDisabled(false);
            ztreeBeans.add(tree);
        }
        return new Result(ztreeBeans);
    }

    /**
     * 获取权限实体
     *
     * @param permissionId 权限id
     * @return 权限实体
     */
    @Override
    public PermissionEntity getPermissionEntity(Long permissionId) {
        PermissionEntity permissionEntity = permissionEntityMapper.selectByPrimaryKey(permissionId);
        return permissionEntity;
    }

    /**
     * 获取所有菜单列表
     */
    private List<GetPermissionTreeResp> getAllPermissionList(List<Long> menuIdList) {
        //查询根菜单列表
        List<GetPermissionTreeResp> menuList = queryListParentId(0L, menuIdList);
        //递归获取子菜单
        getPermissionTreeList(menuList, menuIdList);
        return menuList;
    }

    /**
     * 递归
     */
    private List<GetPermissionTreeResp> getPermissionTreeList(List<GetPermissionTreeResp> menuList, List<Long> menuIdList) {
        List<GetPermissionTreeResp> subMenuList = new ArrayList<GetPermissionTreeResp>();
        for (GetPermissionTreeResp entity : menuList) {
            if (entity.getType() == PermissionTypeEnum.CATALOG.key()) {
                List<GetPermissionTreeResp> children = getPermissionTreeList(queryListParentId(entity.getPermissionId(), menuIdList), menuIdList);
                entity.setChildren(children);
            }
            subMenuList.add(entity);
        }
        return subMenuList;
    }

    public List<GetPermissionTreeResp> queryListParentId(Long parentId, List<Long> permissionIdList) {
        List<GetPermissionTreeResp> permList = permissionInfoMapper.getPermissionInfoByParentId(parentId);
        if (permissionIdList == null) {
            return permList;
        }
        List<GetPermissionTreeResp> userPermissionList = new ArrayList<>();
        for (GetPermissionTreeResp permission : permList) {
            if (permissionIdList.contains(permission.getPermissionId())) {
                userPermissionList.add(permission);
            }
        }
        return userPermissionList;
    }
}
